#include "MemoryStream.h"
#include <cstring>

namespace lhcutils
{

MemoryStream::MemoryStream() : m_buffer(), m_position(0)
{
	;
}

bool MemoryStream::CanRead()
{
	return true;
}

bool MemoryStream::CanWrite()
{
	return true;
}

bool MemoryStream::CanSeek()
{
	return true;
}

boost::int64_t MemoryStream::GetPosition()
{
	return m_position;
}

void MemoryStream::SetPosition(boost::int64_t newPosition, SeekOrigin::Value origin)
{
	boost::int64_t absoluteNewPosition;
	if(origin == SeekOrigin::Begin)
	{
		absoluteNewPosition = newPosition;
	}
	else if(origin == SeekOrigin::Current)
	{
		absoluteNewPosition = m_position + newPosition;
	}
	else
	{
		absoluteNewPosition = m_buffer.size() + newPosition;
	}

	if(absoluteNewPosition < 0)
	{
		absoluteNewPosition = 0;
	}
	else if(absoluteNewPosition > m_buffer.size())
	{
		absoluteNewPosition = m_buffer.size(); // TODO: Support seeking past the end?
	}

	m_position = absoluteNewPosition;
}

void MemoryStream::Flush()
{
	;
}

size_t MemoryStream::Read(void* buffer, size_t count)
{
	size_t numBytesAvailable = m_buffer.size() - m_position;
	size_t numBytesToRead = count;
	if(numBytesAvailable < count)
	{
		numBytesToRead = numBytesAvailable;
	}

	if(numBytesToRead == 0)
	{
		return 0;
	}

	std::memcpy(buffer, &(m_buffer[m_position]), numBytesToRead);
	m_position += numBytesToRead;
	return numBytesToRead;
}

void MemoryStream::Write(const void* buffer, size_t count)
{
	if(m_buffer.size() < m_position + count)
	{
		m_buffer.resize(m_position + count);
	}

	std::memcpy(&(m_buffer[m_position]), buffer, count);
	m_position += count;
}

void MemoryStream::Close()
{
	;
}

MemoryStream::~MemoryStream()
{
	;
}

}

/*
 Copyright 2011 Greg Najda

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
